package com.share.finance.risk.third.aop;

import com.share.finance.risk.common.model.sys.ThirdRequest;
import com.share.finance.risk.third.model.db.InterfaceConfig;
import com.share.finance.risk.third.service.AsyncDealService;
import com.share.finance.risk.third.service.IInterfaceConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Order(1)
@Component
public class DataCacheAspectImpl {
    @Autowired
    private IInterfaceConfigService interfaceConfigService;

    @Autowired
    private AsyncDealService asyncDealService;

    @Autowired
    private CacheApiData cacheApiData;

    //@Within表示匹配类上的指定注解，@annotation表示匹配方法上的指定注解
    @Pointcut("@within(com.share.finance.risk.third.aop.DataCacheAspect) || @annotation(com.share.finance.risk.third.aop.DataCacheAspect)")
    public void dataCacheAspect() {

    }

    /**
     * 调用数据源AOP处理
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("dataCacheAspect()")
    public String around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        ThirdRequest thirdRequest = (ThirdRequest) joinPoint.getArgs()[0];
        InterfaceConfig configPo = interfaceConfigService.getInterfaceConfig(thirdRequest.getIntId());

        //从缓存取数据
        Boolean isCache = true;
        String result = cacheApiData.getDataFromCache(thirdRequest, configPo);
        if (StringUtils.isEmpty(result)) {
            //执行业务
            result = (String) joinPoint.proceed();
            isCache = false;

            //存入缓存---数据层级改变,所以用返回值
            cacheApiData.setDataToCache(thirdRequest, configPo, result);
        }

        //记录调用日志
        asyncDealService.channelRequestLogServiceSaveLog(configPo, thirdRequest, isCache ? null : thirdRequest.getHttpParam(), result, isCache, System.currentTimeMillis() - startTime);

        return result;
    }
}
